//
//  PPFoundTimelineViewController.m
//  pickpic
//
//  Created by GaoYongyue on 16/10/18.
//  Copyright © 2016年 MicroDream. All rights reserved.
//

#import "PPFoundTimelineViewController.h"
#import "PPFanUserListViewController.h"
#import "PPFollowingUserListViewController.h"
#import "PPCommentTimelineViewController.h"
#import "PPUserInfoViewController.h"
#import "PPTimelinePictureViewController.h"
#import "PPMessageTimelineViewController.h"
#import "PPProfileViewController.h"

#import "PPProfileTableViewSectionHeaderView.h"

#import "PPProfileTableViewCommentCell.h"

#import "PPAlbumObject.h"

#import "PPAlbumShareView.h"
#import "PPAlbumShareActionView.h"

#import "PPSocializationManager.h"
#import "PPUnreadMessageManager.h"

static const NSInteger kCount = 30;

@interface PPFoundTimelineViewController () <PPProfileTableViewSectionHeaderViewDelegate, PPCommentTimelineViewControllerDelegate>
@property (readwrite, nonatomic, assign) dispatch_once_t once;
@end

@implementation PPFoundTimelineViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.title = @"发现";

    self.tableView.backgroundColor = [UIColor colorWithRGBHex:0xf2f2f2];

    [self.tableView registerClass:[PPProfileTableViewCommentCell class] forCellReuseIdentifier:@"commentCell"];

    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;

    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor clearColor];
    headerView.frame = CGRectMake(0, 0, CGFLOAT_MIN, CGFLOAT_MIN);
    self.tableView.tableHeaderView = headerView;
}

- (void)viewDidLayoutSubviews {
    [super viewDidLayoutSubviews];

    if(self.items.count > 0) {
        dispatch_once(&_once, ^{
            CGRect rect = [self.tableView rectForSection:_index];
            rect.size.height = self.tableView.height - 64;
            [self.tableView scrollRectToVisible:rect animated:NO];
        });
    }
}

#pragma mark - UITableViewDelegate & UITableViewDataSource

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    PPAlbumObject *album = [self.items safeObjectAtIndex:section];

    return [PPProfileTableViewSectionHeaderView heightForAlbum:album];
}

- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    PPAlbumObject *album = [self.items safeObjectAtIndex:section];

    if(album.commentCount > 3) {
        return 45;
    } else if(album.commentCount == 0) {
        return 15;
    } else {
        return 22;
    }
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    PPAlbumObject *album = [self.items safeObjectAtIndex:indexPath.section];

    PPTimelineCommentObject *comment = [album.comments safeObjectAtIndex:indexPath.row];

    return [PPProfileTableViewCommentCell heightForComment:comment constrainedSize:CGSizeMake(tableView.width, 1000)];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.items.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    PPAlbumObject *album = [self.items safeObjectAtIndex:section];

    return MIN(album.comments.count, 3);
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(nonnull NSIndexPath *)indexPath {
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"commentCell" forIndexPath:indexPath];

    PPAlbumObject *album = [self.items safeObjectAtIndex:indexPath.section];

    PPTimelineCommentObject *comment = [album.comments safeObjectAtIndex:indexPath.row];
    ((PPProfileTableViewCommentCell *)cell).comment = comment;

    return cell;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    PPAlbumObject *album = [self.items safeObjectAtIndex:section];

    PPProfileTableViewSectionHeaderView *headerView = [[NSBundle mainBundle] loadNibNamed:@"PPProfileTableViewSectionHeaderView" owner:nil options:nil].firstObject;
    headerView.backgroundColor = [UIColor clearColor];
    headerView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForHeaderInSection:section]);
    headerView.album = album;
    headerView.delegateViewController = self;
    headerView.delegate = self;

    return headerView;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    UIView *headerView = [[UIView alloc] init];
    headerView.backgroundColor = [UIColor clearColor];
    headerView.frame = CGRectMake(0, 0, tableView.width, [self tableView:tableView heightForFooterInSection:section]);

    UIView *view = [[UIView alloc] init];
    view.frame = CGRectMake(0, 0, headerView.width, headerView.height - 10);
    view.backgroundColor = [UIColor whiteColor];
    [view addBottomBorderWithColor:kLineColor andWidth:kLineWidth];

    PPAlbumObject *album = [self.items safeObjectAtIndex:section];

    if(album.commentCount > 3) {
        UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
        button.titleLabel.font = [UIFont systemFontOfSize:15];
        [button setTitle:[NSString stringWithFormat:@"全部%li条评论", album.commentCount] forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRGBHex:0x999999] forState:UIControlStateNormal];
        button.contentEdgeInsets = UIEdgeInsetsMake(4, 15, 4, 15);
        [button sizeToFit];
        button.frame = CGRectMake(0, 0, button.width, button.height);
        [view addSubview:button];

        __weak typeof(self)weakSelf = self;
        [button setActionBlock:^(UIControl *control) {
            [MobClick event:@"132"];
            PPCommentTimelineViewController *commentViewController = [[PPCommentTimelineViewController alloc] init];
            commentViewController.albumID = album.albumID.integerValue;
            commentViewController.ownerID = album.userID;
            commentViewController.delegate = self;
            commentViewController.userInfo = @(section);
            [weakSelf.navigationController pushViewController:commentViewController animated:YES];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    [headerView addSubview:view];

    return headerView;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [MobClick event:@"130"];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

    PPAlbumObject *album = [self.items safeObjectAtIndex:indexPath.section];

    PPTimelineCommentObject *comment = [album.comments safeObjectAtIndex:indexPath.row];

    PPCommentTimelineViewController *commentViewController = [[PPCommentTimelineViewController alloc] init];
    commentViewController.albumID = album.albumID.integerValue;
    commentViewController.ownerID = album.userID;
    commentViewController.comment = comment;
    commentViewController.delegate = self;
    commentViewController.userInfo = @(indexPath.section);
    [self.navigationController pushViewController:commentViewController animated:YES];
}

- (void)showsEmptyIfNeeded {
    UIView *footerView = [self.scrollWrapper valueForKey:@"footerView"];
    UIActivityIndicatorView *activityView = [self valueForKey:@"loadMoreIndicatorView"];

    UILabel *label = objc_getAssociatedObject(footerView, "emptyLabel");

    if(_next.integerValue != -1) {
        activityView.hidden = NO;
        label.hidden = YES;
    } else {
        activityView.hidden = YES;

        if(label == nil) {
            label = [[UILabel alloc] init];
            label.font = [UIFont systemFontOfSize:14];
            label.textColor = [UIColor colorWithRGBHex:0xb2b2b2];
            label.text = @"已显示全部";
            [label sizeToFit];
            [footerView addSubview:label];

            objc_setAssociatedObject(footerView, "emptyLabel", label, OBJC_ASSOCIATION_RETAIN);
        }

        label.centerX = footerView.width/2;
        label.top = 30;
        label.hidden = NO;
    }
}

#pragma mark - Timeline

- (NSArray *)initialItems {
    NSMutableArray *items = [NSMutableArray array];

    [_albums enumerateObjectsUsingBlock:^(PPAlbumObject *_Nonnull album, NSUInteger idx, BOOL *_Nonnull stop) {

        [album.comments enumerateObjectsUsingBlock:^(PPTimelineCommentObject *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
            NSString *content = nil;

            if(obj.receiver == nil) {
                content = [NSString stringWithFormat:@"\u200B%@: %@", obj.sender.name, obj.content];;
            } else {
                content = [NSString stringWithFormat:@"\u200B%@ 回复 \u200C%@: %@", obj.sender.name, obj.receiver.name, obj.content];
            }

            DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
            editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
            editor.defaultFont = [UIFont systemFontOfSize:15];

            {
                DGCoreTextPatternSetting *senderSetting = [[DGCoreTextPatternSetting alloc] init];
                senderSetting.predicate = @"\u200B[\\u4e00-\\u9fa5\\w\\-]+";
                senderSetting.defaultFont = [UIFont systemFontOfSize:15];
                senderSetting.highlightedFont = [UIFont systemFontOfSize:15];
                senderSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                senderSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                __weak typeof(self)weakSelf = self;
                senderSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                    [weakSelf didPressedCommentSender:obj];
                };
                [editor preprocessWithPatternSetting:senderSetting];
            }

            {
                DGCoreTextPatternSetting *receiverSetting = [[DGCoreTextPatternSetting alloc] init];
                receiverSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
                receiverSetting.defaultFont = [UIFont systemFontOfSize:15];
                receiverSetting.highlightedFont = [UIFont systemFontOfSize:15];
                receiverSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                receiverSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                __weak typeof(self)weakSelf = self;
                receiverSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                    [weakSelf didPressedCommentReceiver:obj];
                };
                [editor preprocessWithPatternSetting:receiverSetting];
            }

            [editor process];

            obj.editor = editor;
        }];

        [items addObject:album];
    }];

    if([_next integerValue] != -1) {
        self.scrollWrapper.enableLoadMore = YES;
    } else {
        self.scrollWrapper.enableLoadMore = NO;
    }

    self.tableView.tableFooterView = nil;
    
    return items;
}

- (void)fetchNewItems {
    [super fetchNewItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchDiscoverWithPage:@(1) limit:@(kCount) callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [strongSelf didReceiveNewResult:data ? : error];
    }];
}

- (void)fetchMoreItems {
    [MobClick event:@"136"];
    [super fetchMoreItems];

    __weak typeof(self)weakSelf = self;
    [PPNetworkService fetchDiscoverWithPage:@(_page + 1) limit:@(kCount) callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        [strongSelf didReceiveMoreResult:data ? : error];
    }];
}

- (NSArray *)didReceiveNewResult:(id)result {
    _page = 1;
    NSArray *items = [super didReceiveNewResult:result];

    [self showsEmptyIfNeeded];

    return items;
}

- (NSArray *)didReceiveMoreResult:(id)result {
    _page ++;
    NSArray *items = [super didReceiveMoreResult:result];

    [self showsEmptyIfNeeded];

    return items;
}

- (NSArray *)itemsFromResult:(id)result {
    NSMutableArray *items = [NSMutableArray array];

    self.next = [[result validDictionary] validNumberForKey:@"next"];

    for(NSDictionary *parameters in [result validArrayForKey:@"albums"]) {

        PPAlbumObject *album = [PPAlbumObject albumForParameters:parameters];

        [album.comments enumerateObjectsUsingBlock:^(PPTimelineCommentObject *_Nonnull obj, NSUInteger idx, BOOL *_Nonnull stop) {
            NSString *content = nil;

            if(obj.receiver == nil) {
                content = [NSString stringWithFormat:@"\u200B%@: %@", obj.sender.name, obj.content];;
            } else {
                content = [NSString stringWithFormat:@"\u200B%@ 回复 \u200C%@: %@", obj.sender.name, obj.receiver.name, obj.content];
            }

            DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
            editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
            editor.defaultFont = [UIFont systemFontOfSize:15];

            {
                DGCoreTextPatternSetting *senderSetting = [[DGCoreTextPatternSetting alloc] init];
                senderSetting.predicate = @"\u200B[\\u4e00-\\u9fa5\\w\\-]+";
                senderSetting.defaultFont = [UIFont systemFontOfSize:15];
                senderSetting.highlightedFont = [UIFont systemFontOfSize:15];
                senderSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                senderSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                __weak typeof(self)weakSelf = self;
                senderSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                    [weakSelf didPressedCommentSender:obj];
                };
                [editor preprocessWithPatternSetting:senderSetting];
            }

            {
                DGCoreTextPatternSetting *receiverSetting = [[DGCoreTextPatternSetting alloc] init];
                receiverSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
                receiverSetting.defaultFont = [UIFont systemFontOfSize:15];
                receiverSetting.highlightedFont = [UIFont systemFontOfSize:15];
                receiverSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
                receiverSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

                __weak typeof(self)weakSelf = self;
                receiverSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
                    [weakSelf didPressedCommentReceiver:obj];
                };
                [editor preprocessWithPatternSetting:receiverSetting];
            }

            [editor process];

            obj.editor = editor;
        }];

        [items addObject:album];
    }

    return items;
}

- (UITableViewStyle)preferredTableViewStyle {
    return UITableViewStyleGrouped;
}

- (void)didPressedCommentSender:(PPTimelineCommentObject *)comment {
    [MobClick event:@"131"];
    PPProfileViewController *profileViewController = [[PPProfileViewController alloc] init];
    profileViewController.userID = comment.sender.userID;
    [self.navigationController pushViewController:profileViewController animated:YES];
}

- (void)didPressedCommentReceiver:(PPTimelineCommentObject *)comment {
    PPProfileViewController *profileViewController = [[PPProfileViewController alloc] init];
    profileViewController.userID = comment.receiver.userID;
    [self.navigationController pushViewController:profileViewController animated:YES];
}

#pragma mark - Share

- (void)didSelectShareAlbum:(PPAlbumObject *)album {

    __block NSError *error_ = nil;
    __block NSString *title = nil;
    __block NSString *subtitle = nil;
    __block NSString *url = nil;
    __block UIImage *image_ = nil;
    __block NSString *pickpic = nil;

    dispatch_group_t group = dispatch_group_create();

    __weak typeof(self)weakSelf = self;

    dispatch_group_enter(group);
    [PPNetworkService getShareInfoWithAlbumID:album.albumID callback:^(id data, NSError *error) {
        __strong typeof(weakSelf)strongSelf = weakSelf;

        if(strongSelf == nil) {
            return;
        }

        if(error == nil) {
            title = [data validStringForKey:@"title"];
            subtitle = [data validStringForKey:@"title2"];
            url = [data validStringForKey:@"url"];
            pickpic = [data validStringForKey:@"pickpic"];
        } else {
            error_ = error;
        }

        dispatch_group_leave(group);

    }];

    dispatch_group_enter(group);
    [album queryCoverImageWithCompletion:^(UIImage *image, NSError *error) {
        if(error == nil) {
            image_ = image;
        } else {
            error_ = error;
        }

        dispatch_group_leave(group);
    }];

    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.navigationController.view animated:YES];

    dispatch_group_notify(group, dispatch_get_main_queue(), ^{

        [hud hide:YES];

        if(error_ != nil) {
            [self.navigationController.view toastMessage:error_.networkPrompt];
        } else {
            [self shareAlbum:album title:title subtitle:subtitle url:url image:image_ pickpic:pickpic];
        }
    });
}

- (void)shareAlbum:(PPAlbumObject *)album title:(NSString *)title subtitle:(NSString *)subtitle url:(NSString *)url image:(UIImage *)image pickpic:(NSString *)pickpic {

    UIView *actionView = nil;

    if([[PPSocializationManager sharedInstance] support:PPSocializationTypeWeixin] && [[PPSocializationManager sharedInstance] support:PPSocializationTypeQQ]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:4];
    } else if([[PPSocializationManager sharedInstance] support:PPSocializationTypeWeixin]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:5];
    } else if([[PPSocializationManager sharedInstance] support:PPSocializationTypeQQ]) {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:6];
    } else {
        actionView = [[[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareActionView" owner:nil options:nil] safeObjectAtIndex:7];
    }

    UIView *displayView = self.navigationController.view;

    PPAlbumShareView *shareView = [[NSBundle mainBundle] loadNibNamed:@"PPAlbumShareView" owner:nil options:nil].firstObject;
    shareView.alpha = 0;
    shareView.frame = displayView.bounds;
    shareView.cover = image;
    shareView.avatarURLString = album.ownerAvatar;
    shareView.name = album.ownerName;
    shareView.account = pickpic;
    shareView.title = album.title;
    [displayView addSubview:shareView];

    shareView.titleLabel.hidden = YES;
    UIImage *thumbnail = [shareView.contentView snapshotImage];
    shareView.titleLabel.hidden = NO;
    image = [shareView.contentView snapshotImage];

    actionView.frame = CGRectMake(0, displayView.height - actionView.height, displayView.width, actionView.height);

    DGPopoverView *popoverView = [[DGPopoverView alloc] initWithContainerView:displayView contentView:actionView options:DGPopoverViewAnimationOptionUpward backgroundStyle:DGPopoverViewBackgroundStyleNone];

    __weak typeof(popoverView)weakPopover = popoverView;

    if([actionView respondsToSelector:@selector(wechatButton)]) {
        UIButton *wechatButton = [actionView valueForKey:@"wechatButton"];
        [wechatButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{

                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeWeixinChat];

            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(circleButton)]) {
        UIButton *circleButton = [actionView valueForKey:@"circleButton"];
        [circleButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{

                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeWeixinCircle];

            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(weiboButton)]) {
        UIButton *weiboButton = [actionView valueForKey:@"weiboButton"];
        [weiboButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{

                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeWeibo];

            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(qqButton)]) {
        UIButton *qqButton = [actionView valueForKey:@"qqButton"];
        [qqButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:^{

                [[PPSocializationManager sharedInstance] shareTitle:title subtitle:subtitle url:url image:image thumbnail:thumbnail type:PPSocializationShareTypeQQChat];

            }];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    if([actionView respondsToSelector:@selector(cancelButton)]) {
        UIButton *cancelButton = [actionView valueForKey:@"cancelButton"];
        [cancelButton setActionBlock:^(UIControl *control) {
            [weakPopover dismissAnimated:YES completion:nil];
        } forControlEvents:UIControlEventTouchUpInside];
    }

    popoverView.willDisplayBlock = ^{

        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            shareView.alpha = 1;
        } completion:nil];

    };

    popoverView.willDismissBlock = ^{

        [UIView animateWithDuration:0.25 delay:0 options:UIViewAnimationOptionBeginFromCurrentState animations:^{
            shareView.alpha = 0;
        } completion:^(BOOL finished) {
            [shareView removeFromSuperview];
        }];

    };

    [popoverView displayAnimated:YES completion:nil];
}

#pragma mark - PPProfileTableViewSectionHeaderViewDelegate

- (void)sectionHeaderView:(PPProfileTableViewSectionHeaderView *)sectionHeaderView didSelectShareAlbum:(PPAlbumObject *)album {
    [self didSelectShareAlbum:album];
}

- (void)sectionHeaderView:(PPProfileTableViewSectionHeaderView *)sectionHeaderView didSelectCommentListForAlbum:(PPAlbumObject *)album {
    NSInteger section = [self.items indexOfObject:album];

    PPCommentTimelineViewController *commentViewController = [[PPCommentTimelineViewController alloc] init];
    commentViewController.albumID = album.albumID.integerValue;
    commentViewController.ownerID = album.userID;
    commentViewController.delegate = self;
    commentViewController.userInfo = @(section);
    [self.navigationController pushViewController:commentViewController animated:YES];
}

- (UIView *)emptyPromptViewForError:(NSError *)error {
    if(error != nil) {
        UILabel *label = [[UILabel alloc] init];
        label.text = error.networkPrompt;
        label.font = [UIFont systemFontOfSize:14];
        label.textColor = [UIColor colorWithRGBHex:0x999999];
        [label sizeToFit];

        return label;
    } else {
        DGAlignmentButton *button = [DGAlignmentButton buttonWithType:UIButtonTypeCustom];
        button.style = DGAlignmentButtonStyleImageTop;
        button.spacing = 10;
        button.titleLabel.font = [UIFont systemFontOfSize:14];
        button.contentEdgeInsets = UIEdgeInsetsMake(20, 20, 20, 20);
        [button setImage:[UIImage imageNamed:@"logo-gred"] forState:UIControlStateNormal];
        [button setTitle:@"暂无内容" forState:UIControlStateNormal];
        [button setTitleColor:[UIColor colorWithRGBHex:0x999999] forState:UIControlStateNormal];
        [button sizeToFit];

        return button;
    }
}

#pragma mark - PPCommentTimelineViewControllerDelegate

- (void)commentTimelineViewController:(PPCommentTimelineViewController *)commentTimelineViewController didInsertComment:(PPTimelineCommentObject *)comment {
    NSInteger section = [commentTimelineViewController.userInfo integerValue];

    PPAlbumObject *album = [self.items safeObjectAtIndex:section];

    NSMutableArray *comments = [NSMutableArray arrayWithArray:album.comments];

    if(comments.count == 3) {
        [comments removeLastObject];
    }

    NSString *content = nil;

    if(comment.receiver == nil) {
        content = [NSString stringWithFormat:@"\u200B%@: %@", comment.sender.name, comment.content];;
    } else {
        content = [NSString stringWithFormat:@"\u200B%@ 回复 \u200C%@: %@", comment.sender.name, comment.receiver.name, comment.content];
    }

    DGCoreTextEditor *editor = [[DGCoreTextEditor alloc] initWithString:content];
    editor.defaultColor = [UIColor colorWithRGBHex:0x4d4d4d];
    editor.defaultFont = [UIFont systemFontOfSize:15];

    {
        DGCoreTextPatternSetting *senderSetting = [[DGCoreTextPatternSetting alloc] init];
        senderSetting.predicate = @"\u200B[\\u4e00-\\u9fa5\\w\\-]+";
        senderSetting.defaultFont = [UIFont systemFontOfSize:15];
        senderSetting.highlightedFont = [UIFont systemFontOfSize:15];
        senderSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
        senderSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

        __weak typeof(self)weakSelf = self;
        senderSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
            [weakSelf didPressedCommentSender:comment];
        };
        [editor preprocessWithPatternSetting:senderSetting];
    }

    {
        DGCoreTextPatternSetting *receiverSetting = [[DGCoreTextPatternSetting alloc] init];
        receiverSetting.predicate = @"\u200C[\\u4e00-\\u9fa5\\w\\-]+";
        receiverSetting.defaultFont = [UIFont systemFontOfSize:15];
        receiverSetting.highlightedFont = [UIFont systemFontOfSize:15];
        receiverSetting.defaultColor = [UIColor colorWithRGBHex:0x2d3d78];
        receiverSetting.highlightedColor = [UIColor colorWithRGBHex:0x2d3d78];

        __weak typeof(self)weakSelf = self;
        receiverSetting.actionBlock = ^(DGCoreTextPattern *pattern) {
            [weakSelf didPressedCommentReceiver:comment];
        };
        [editor preprocessWithPatternSetting:receiverSetting];
    }

    [editor process];

    comment.editor = editor;

    [comments insertObject:comment atIndex:0];

    album.comments = comments;

    album.commentCount++;

    [self.tableView reloadData];
}

- (void)commentTimelineViewController:(PPCommentTimelineViewController *)commentTimelineViewController didRemoveComment:(PPTimelineCommentObject *)comment {
    NSInteger section = [commentTimelineViewController.userInfo integerValue];

    PPAlbumObject *album = [self.items safeObjectAtIndex:section];

    PPTimelineCommentObject *removedComment = nil;

    NSMutableArray *comments = [NSMutableArray arrayWithArray:album.comments];

    for(PPTimelineCommentObject *comment_ in comments) {
        if([comment.commentID isEqual:comment_.commentID]) {
            removedComment = comment_;
            break;
        }
    }

    album.commentCount--;

    if(removedComment != nil) {
        [comments removeObject:removedComment];

        album.comments = comments;
    }

    [self.tableView reloadData];
}

- (BOOL)prefersRefreshAutomatically {
    return NO;
}

- (BOOL)scrollViewWrapperShouldTriggerLoadMore:(DGScrollViewWrapper *)scrollViewWrapper {
    if(_next.integerValue != -1) {
        return YES;
    }
    return NO;
}

@end
